package com.itheima.fanshe;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * @Author:gy
 * @Date: 2025/09/06 15:04
 * @Description:
 */
public class Demo {
    public static void main(String[] args) throws Exception {
        //字节流去加载配置文件
        FileInputStream fis = new FileInputStream("Day15\\src\\conf.properties");
        //创建一个map集合
        Properties prop = new Properties();
        prop.load(fis);
        //System.out.println(prop);
        String className = prop.getProperty("className");
        //创建字节码对象
        Class clazz = Class.forName(className);
        Object o = clazz.newInstance();
        //遍历配置文件中所有的属性
        for (String key : prop.stringPropertyNames()) {
           //跳过className,不进行赋值
            if("className".equals(key)){
                continue;
            }
            String value = prop.getProperty(key);
            //获取当前字节码的对象的属性  如果不是本类的属性  这里会报错
            try {
                Field field = clazz.getDeclaredField(key);
                field.setAccessible(true);
                //根据字段类型进行赋值
                if(field.getType() == String.class){
                    field.set(o,value);
                }else if(field.getType() == int.class){
                    field.set(o,Integer.parseInt(value));
                }
            } catch (NoSuchFieldException e) {
                //throw new RuntimeException(e);
            } catch (SecurityException e) {
                throw new RuntimeException(e);
            } catch (IllegalArgumentException e) {
                throw new RuntimeException(e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
        System.out.println("通过配置文件创建了对象,并赋值,结果是"+o);
    }
}
